#include "devicemonitor.h"
#include "receive_processor.h"
DeviceMonitor::DeviceMonitor(QWidget *parent)
    : QWidget{parent}
{
    // 初始化样式
    setupUI();
    setupConnections();
}


void DeviceMonitor::setupUI() {
    // 主布局（添加边距控制）
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(5, 5, 5, 5);  // 整体边距
    mainLayout->setSpacing(10);                   // 控件间距

    // 侧边栏列表（添加样式类名）
    device_Tree = new QTreeWidget();
    device_Tree->setObjectName("deviceTree");
    // device_Tree->addItem("总览");
    // deviceList->addItems({"设备1", "设备2", "设备3"});
    device_Tree->setMinimumWidth(180);  // 最小宽度
    device_Tree->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

    // 堆叠窗口（设置拉伸因子）
    stackedWidget = new QStackedWidget();
    stackedWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 创建页面
    // createOverviewPage();
    // createDevicePages();
    L_green=new QPixmap("./Resource/L_green.tiff");
    L_red=new QPixmap("./Resource/L_red.tiff");
    L_gray=new QPixmap("./Resource/L_gray.tiff");
    L_yellow=new QPixmap("./Resource/L_yellow.tiff");
    Warning_Light_List=new QList<QLabel*>;
    param_out_of_setting=new QList<QList<bool>*>;

    mainLayout->addWidget(device_Tree, 1);        // 左侧占1份宽度
    mainLayout->addWidget(stackedWidget, 4);     // 右侧占4份宽度
}

// 在createOverviewPage函数中
int DeviceMonitor::update_construct(QList<Receive_Processor*> *receive_processors) {
    last_update_list=new QList<QLabel*>;
    device_labels=new QList<QList<QLabel*>*>;
    device_out_of_top_labels=new QList<QList<QLabel*>*>;
    tree_item_list=new QList<QTreeWidgetItem*>;
    param_components=new QList<QList<ChartComponents*>*>;
    devices_param_data=new QList<QVector<double>*>;
    //循环遍历所有处理器
    for (int i = 0; i < receive_processors->count(); ++i) {
        //==========================================================
        //警报相关
        QList<bool> *page_out_of_setting=new QList<bool>;
        param_out_of_setting->push_back(page_out_of_setting);
        QLabel *Warning_Light=new QLabel;
        Warning_Light_List->push_back(Warning_Light);
        Warning_Light->setPixmap(*L_gray);
        // Warning_Light->setScaledContents(true);
        Warning_Light->setFixedSize(250,250);
        QList<QLabel*> *out_of_top_labels=new QList<QLabel*>;
        device_out_of_top_labels->push_back(out_of_top_labels);
        out_of_top_labels->push_back(new QLabel("是否超出阈值"));
        //====================================================
        //处理器的页面
        QWidget *page = new QWidget();
        stackedWidget->addWidget(page);

        //处理器的页面布局
        QGridLayout *grid = new QGridLayout(page);
        grid->setContentsMargins(5, 5, 5, 5);
        grid->setSpacing(10);
        // grid->setAlignment(Qt::)
        QGroupBox *group = new QGroupBox(QString("设备 %1 地址%2").arg(i+1).arg(receive_processors->value(i)->address));
        group->setObjectName("deviceCard");
        //============================================================================
        //设备的树节点
        QTreeWidgetItem *device=new QTreeWidgetItem(QStringList() << QString("设备 %1 地址%2").arg(i+1).arg(receive_processors->value(i)->address));
        tree_item_list->push_back(device);

        device_Tree->addTopLevelItem(device);
        QHBoxLayout *page_hlayout=new QHBoxLayout();
        group->setLayout(page_hlayout);

        //实时数据
        QVBoxLayout *vbox = new QVBoxLayout();
        //更能耗参数的阈值的垂直布局
        QVBoxLayout *top_value_vlayout=new QVBoxLayout();
        top_value_vlayout->setAlignment(Qt::AlignLeft);
        QLabel *top_value_label=new QLabel("能耗阈值");
        top_value_vlayout->addWidget(top_value_label);
        //该能后数据是否超出阈值
        QVBoxLayout *out_of_top_vlayout=new QVBoxLayout();
        out_of_top_vlayout->setAlignment(Qt::AlignLeft);
        QLabel *out_of_top_value_label=new QLabel("是否超出阈值");
        out_of_top_vlayout->addWidget(out_of_top_value_label);


        QList<QLabel*> *labels=new QList<QLabel*>;
        QString customFormat = "yyyy-MM-dd   HH ：mm ：ss\t"; // 年-月-日 时:分:秒
        QLabel *last_update_time=new QLabel(QString("最后更新时间:")+ receive_processors->value(i)->last_update.toString(customFormat));
        last_update_list->push_back(last_update_time);//保存最后更新时间的列表
        vbox->addWidget(last_update_time);
        vbox->setSpacing(8);
        page_hlayout->addLayout(vbox,3);
        page_hlayout->addLayout(top_value_vlayout,3);
        page_hlayout->addLayout(out_of_top_vlayout,3);
        page_hlayout->addWidget(Warning_Light,1);
        //对于每个接收处理器的进行单独的数据显示
        QList<ChartComponents*> *chartcomponents=new QList<ChartComponents*>;
        for(int j=0;j<receive_processors->value(i)->annotation_list->count();j++)
        {
            //是否超过阈值相关代码
            QLabel *temp_out_of_top=new QLabel("否");
            out_of_top_labels->push_back(temp_out_of_top);
            page_out_of_setting->push_back(false);
            out_of_top_vlayout->addWidget(temp_out_of_top);
            //处理器的参数的图表数据的容器
            QVector<double> *param_show_collections=new QVector<double>;
            devices_param_data->push_back(param_show_collections);

            Receive_Processor *processor_temp=receive_processors->value(i);
            QLabel *temp_label=createStatusLabel(processor_temp->annotation_list->value(j));//获取对应的解释名称
            double top_value=processor_temp->top_value_list->value(j);
            top_value_vlayout->addWidget(new QLabel(QString::number(top_value)));
            temp_label->setAlignment(Qt::AlignLeft);
            labels->push_back(temp_label);
            // qDebug()<<receive_processors->value(i)->annotation_list->value(j);
            vbox->addWidget(temp_label);
            //将参数添加到树形视图的子项
            QTreeWidgetItem *childItem = new QTreeWidgetItem(QStringList() << processor_temp->annotation_list->value(j));
            device->addChild(childItem);
            // single_device_params->push_back(childItem);
            tree_item_list->push_back(childItem);
            //为每个参数创建图标
            QWidget *page_param = new QWidget();
            QVBoxLayout *layout = new QVBoxLayout(page_param);
            layout->setContentsMargins(0, 0, 0, 0);
            // // 创建图表
            QChart *chart = new QChart();
            //数值列表
            QLineSeries *value_series = new QLineSeries();
            //报警值序列
            QLineSeries *warning_series=new QLineSeries();
            warning_series->setColor(Qt::red);
            warning_series->setName(receive_processors->value(i)->annotation_list->value(j)+"阈值");

            value_series->setName(receive_processors->value(i)->annotation_list->value(j));
            chart->addSeries(value_series);
            chart->addSeries(warning_series);
            // // 坐标轴
            QValueAxis *axisX = new QValueAxis();

            int x_range=200;
            axisX->setRange(0, x_range);
            axisX->setTitleText("时间");
            QValueAxis *axisY = new QValueAxis();
            //根据处理器的参数的数据大小来设置Y轴的高度
            axisY->setRange(0,1);
            axisY->setTitleText("数值");
            chart->addAxis(axisX, Qt::AlignBottom);
            chart->addAxis(axisY, Qt::AlignLeft);
            value_series->attachAxis(axisX);
            value_series->attachAxis(axisY);
            warning_series->attachAxis(axisX);
            warning_series->attachAxis(axisY);
            for(int z=0;z<x_range;z++)
            {
                warning_series->append(z,receive_processors->value(i)->top_value_list->value(j));
            }

            QChartView *chartView = new QChartView(chart);
            chartView->setRenderHint(QPainter::Antialiasing);
            chartView->setObjectName("chartView");
            // // 当前值显示
            QWidget *statusWidget = new QWidget();
            QHBoxLayout *statusLayout = new QHBoxLayout(statusWidget);
            QLabel *value_label = new QLabel();

            statusLayout->addWidget(value_label);
            layout->addWidget(chartView);
            layout->addWidget(statusWidget);
            // // 保存图表相关对象
            ChartComponents *param_component_temp=new ChartComponents{chart,value_series,value_label,axisX,axisY};
            chartcomponents->push_back(param_component_temp);
            stackedWidget->addWidget(page_param);

        }
        //保存各变量
        device_labels->push_back(labels);
        param_components->push_back(chartcomponents);
        // qDebug()<<"设备0包含的图标子项数目:"<<param_components->value(0)->count();
        grid->addWidget(group, i/2, i%2);
        device_Tree->expandItem(device);//展开显示设备的树节点

    }


    return 1;
}

QLabel* DeviceMonitor::createStatusLabel(const QString &title)
{
    QLabel *label = new QLabel(title + ": --");
    label->setObjectName("statusLabel");
    label->setAlignment(Qt::AlignCenter);
    return label;

}

void DeviceMonitor::setupConnections()
{
    // 列表选择变化
    connect(device_Tree,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(change_page(QTreeWidgetItem*,int)));
}

void DeviceMonitor::change_page(QTreeWidgetItem* clicked_item,int column)
{
    for(int i=0;i<tree_item_list->count();i++)
    {
        if(tree_item_list->value(i)==clicked_item)
        {
            stackedWidget->setCurrentIndex(i);
            break;
        }
    }
}

void DeviceMonitor::updateData(QList<Receive_Processor*> *receive_processors,int index)
{
    QString customFormat = "yyyy-MM-dd   HH ：mm ：ss\t"; // 年-月-日 时:分:秒

    //更新设备页面的最后更新时间
    QLabel* last_update_label= last_update_list->value(index);
    last_update_label->setText("最后更新时间:    "+QDateTime::currentDateTime().toString(customFormat));
    param_out_of_setting->value(index)->clear();

    Warning_Light_List->value(index)->setPixmap(*L_green);
    bool exception=false;
    //对于每个采集设备的能耗参数
    for(int j=0;j<device_labels->value(index)->count();j++)
    {
        //更新设备页标签数据
        device_labels->value(index)->value(j)->setText(receive_processors->value(index)->annotation_list->value(j)+":"
        +QString::number((receive_processors->value(index)->real_value_list->value(j))));

        if(receive_processors->value(index)->real_value_list->value(j)>receive_processors->value(index)->top_value_list->value(j))
        {
            this->param_out_of_setting->value(index)->push_back(true);
            this->device_out_of_top_labels->value(index)->value(j)->setText("是");
            exception=true;
        }else
        {
            this->param_out_of_setting->value(index)->push_back(false);
            this->device_out_of_top_labels->value(index)->value(j)->setText("否");
        }

        //更新各参数的页面中图表数据
        QVector<double> *showing_data_collection=devices_param_data->value(j);
        double value=receive_processors->value(index)->real_value_list->value(j);
        //循环将数据添加入容器，这里只添加一个数据
        showing_data_collection->append(value);
        //若插入的值大于当前数据轴的Y轴最大值，则动态更新Y轴的最大值以跟踪显示
        if(value>param_components->value(index)->value(j)->Axis_Y->max())
        {
            param_components->value(index)->value(j)->Axis_Y->setMax(value*1.4);
        }
        // qDebug()<<"index:"<<index<<" ,j:"<<j<<" ,插入的值:"<<receive_processors->value(index)->real_value_list->value(j);
        if(showing_data_collection->size()>200)
        {
            showing_data_collection->removeFirst();
        }
        //清空值序列
        param_components->value(index)->value(j)->valueSeries->clear();
        //对于每个参数的容器中的元素
        //重写值容器到值序列
        for(int z=0;z<showing_data_collection->size();z++)
        {
            param_components->value(index)->value(j)->valueSeries->append(z,showing_data_collection->value(z));
            // qDebug()<<z<<":"<<showing_data_collection->value(z);
        }
    }


    //如果有能耗参数为异常状态
    if(exception)Warning_Light_List->value(index)->setPixmap(*L_red);
}

void DeviceMonitor::configureChart(QChart *chart)
{
    chart->setBackgroundRoundness(5);
    chart->setMargins(QMargins(10, 10, 10, 10));
    chart->legend()->setAlignment(Qt::AlignBottom);

    // 坐标轴样式
    QValueAxis *axisX = new QValueAxis();
    axisX->setGridLineVisible(true);
    axisX->setMinorGridLineVisible(false);

    QValueAxis *axisY = new QValueAxis();
    axisY->setLabelFormat("%.1f");
    axisY->setGridLineVisible(true);
}

QWidget* DeviceMonitor::createCurrentValueBar()
{
    QWidget *bar = new QWidget();
    bar->setObjectName("valueBar");
    QHBoxLayout *layout = new QHBoxLayout(bar);
    layout->setContentsMargins(15, 8, 15, 8);

    QStringList labels = {"电压：-- V", "电流：-- A", "功率：-- W"};
    foreach (const QString &text, labels) {
        QLabel *label = new QLabel(text);
        label->setObjectName("currentValue");
        layout->addWidget(label);
    }

    return bar;
}
